#---------------------------------------------------------
# Are Intermediary Constraints Priced?
# Du, Hébert, Huber
# The Review of Financial Studies 2022
#---------------------------------------------------------

#---------------------------------------------------------
# Format tables and graphs for the paper
# Figures: 2, 5, A1, A2, A3, A4
# Tables: 1, 2, 3, 4, A2, A3, A4, A5, A6, A7, A8, A12, A31, A32
#---------------------------------------------------------

#---------------------------------------------------------
# Set-up
#---------------------------------------------------------

if (exists('script_path')) {
  rm(list = setdiff(ls(), 'script_path'))
} else {
  args = commandArgs(trailingOnly = T)
  if (length(args) > 0) {
    script_path <- args[1]  
    rm(list = setdiff(ls(), 'script_path'))
  } else {
    rm(list = ls())
    script_path <- '~/Dropbox/ForwardArbitrage/CodeReplication/'
  } 
}

# Inputs
library(stargazer)
library(reshape2)
source(paste0(script_path, 'RCode/ArbFunc.R'))
load(paste0(script_path, 'OutputInterim/All_Rates_Dates_Basis_Returns.RData'))
load(paste0(script_path, 'OutputInterim/Basis_and_Returns.RData')) 
load(paste0(script_path, 'OutputInterim/Settlement_AllDays.RData'))
load(paste0(script_path, 'OutputInterim/return_summary.RData')) 
load(paste0(script_path, 'OutputInterim/Factors_And_Test_Assets_Monthly.RData'))
hkm <- fread(paste0(script_path, 'DataSkeleton/AssetClasses/He_Kelly_Manela_Factors_Monthly.csv'))
pc <- fread(paste0(script_path, 'OutputInterim/clean_arbitrage_basis_pc1_monthly_final.csv'))
near_arb <- fread(paste0(script_path, 'OutputInterim/clean_arbitrage_basis_final.csv'))
repo_tsy <- fread(paste0(script_path, 'DataSkeleton/AssetClasses/gross_repo_tsy.csv'))
rate_gcf <- fread(paste0(script_path, 'DataSkeleton/AssetClasses/GCF_Rate.csv'))
rate_tpr <- data.table(read_excel(paste0(script_path, 'DataSkeleton/AssetClasses/TPR_Rate_All.xlsx'), sheet = 'Treasury'))
rate_pd_tsy <- fread(paste0(script_path, 'DataSkeleton/AssetClasses/HistoricalOvernightTreasGCRepoPriDealerSurvRate.csv'))

# Initialization
currency_names6 <- generate_currency_names(number_of_currencies = 6)
currency_names_single <- paste(single_table$fund_currency, single_table$invest_currency, sep = '_')

# Merge in PC with Basis
pc[, `:=` (year = as.numeric(substr(month, 1, 4)),
           mm = as.numeric(substr(month, unlist(gregexpr('m', month)) + 1, 99)))]
pc[, `:=` (Date = as.numeric(paste0(year, sprintf('%02d', mm))),
           scaled_pc_third = pc1 / 3)]
pc <- merge(pc, portfolio_monthly[, .(Date, factor_ois_spot_3M_classic_carry)], by = 'Date', all.x = T)
pc[, `:=` (classic_carry = factor_ois_spot_3M_classic_carry,
           scaled_pc = scaled_pc_third - mean(pc[Date < 201007, scaled_pc_third], na.rm = T))]

#---------------------------------------------------------
# Figure 2: Term structure - OPTION A; grouped HML; full forward tenors
#---------------------------------------------------------

rates_and_dates <- create_sample_period(number_of_periods = number_of_periods, data_table = rates_and_dates,
                                        date_variable = 'Date', period_order = period_order)

for (rate in c('ois')) {
  if (rate == 'ois') {
    currency_names <- currency_names6
  } else if (rate == 'ibor') {
    currency_names <- currency_names6
  }
  
  for (c in c(which(currency_names == 'AUD'), which(currency_names == 'JPY'))) {
    ts_data <- rates_and_dates[Date >= start_date & Date <= extended_end_date, c('Date', 'period', paste(currency_names[c], 'USD', rate, 'spot_log_basis_3M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'spot_log_basis_1M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'log_basis_1M_fwd_1M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'log_basis_2M_fwd_1M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'log_basis_3M_fwd_1M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'log_basis_4M_fwd_2M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'log_basis_6M_fwd_3M', sep = '_'),
                                                                                 paste(currency_names[c], 'USD', rate, 'log_basis_9M_fwd_3M', sep = '_')), with = FALSE]
    names(ts_data) <- c('Date', 'period', 'spot_3M', 'spot 1M', '1M-fwd 1M', '2M-fwd 1M', '3M-fwd 1M', '4M-fwd 2M', '6M-fwd 3M', '9M-fwd 3M')
    ts_data <- ts_data[complete.cases(ts_data)]
    
    for (p in 'Post-Crisis') {
      temp_cut <- ts_data[period == p, ]
      low_mid_cutoff <- quantile(temp_cut$spot_3M, 1/3)
      mid_high_cutoff <- quantile(temp_cut$spot_3M, 2/3)
      
      graph_low <- temp_cut[spot_3M <= low_mid_cutoff, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = names(ts_data)[!(names(ts_data) %in% c('Date', 'period'))]]
      graph_mid <- temp_cut[spot_3M > low_mid_cutoff & spot_3M <= mid_high_cutoff, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = names(ts_data)[!(names(ts_data) %in% c('Date', 'period'))]]
      graph_high <- temp_cut[spot_3M > mid_high_cutoff, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = names(ts_data)[!(names(ts_data) %in% c('Date', 'period'))]]
      
      # Bucket by spot 3M but graph spot 1M
      graph_data <- data.frame(t(rbind(graph_low[, -1], graph_mid[, -1], graph_high[, -1])))
      names(graph_data) <- c('Low', 'Medium', 'High')
      graph_data$tenor <- factor(c('spot 1M', '1M-fwd 1M', '2M-fwd 1M', '3M-fwd 1M', '4M-fwd 2M', '6M-fwd 3M', '9M-fwd 3M'),
                                 levels = c('spot 1M', '1M-fwd 1M', '2M-fwd 1M', '3M-fwd 1M', '4M-fwd 2M', '6M-fwd 3M', '9M-fwd 3M'))
      
      temp_title <- paste(currency_names[c])
      temp_file <- paste(currency_names[c], rate, p, 'TS_fwd_full', sep = '_')
      ggplot(data = reshape2::melt(graph_data, id.vars = 'tenor', variable.name = 'Buckets by Spot 3M', value.name = 'Value'),
             mapping = aes(x = tenor, y = Value * 100, colour = `Buckets by Spot 3M`, group = `Buckets by Spot 3M`)) +
        geom_line() +
        geom_point() +
        labs(x = 'Tenor of Basis', y = 'Basis Points', title = temp_title) +
        geom_hline(yintercept = 0) +
        theme_chart
      ggsave(filename = paste0(script_path, 'OutputFinal/', temp_file, '.png'), width = 20, height = 12, dpi = 300, units = 'cm')
    }
  }
}

#---------------------------------------------------------
# Figure 5: Correlation of the Classic Carry factor vs. HKM (market, int. equity, factor)
#---------------------------------------------------------

graph_data <- merge(portfolio_monthly[, c('Date', 'factor_ois_spot_3M_classic_carry', 'Mkt'), with = FALSE],
                    hkm[, c('yyyymm', 'intermediary_capital_ratio', 'intermediary_value_weighted_investment_return'), with = FALSE],
                    by.x = 'Date', by.y = 'yyyymm')
names(graph_data) <- c('Date', 'basis_orig', 'mkt_return', 'hkm_orig', 'int_return')
graph_data[, daily_date := ymd(paste0(Date, '01'))]
graph_data <- graph_data[daily_date >= start_date & daily_date <= extended_end_date]
graph_data[, `:=` (int_equity = cumprod(1 + int_return),
                   market = cumprod(1 + mkt_return))]

# Create Date variable & scale up Basis Factor
graph_data[, `:=` (basis_scaled = basis_orig * 200,
                   hkm_scaled = hkm_orig * 30)]

(ggplot(data = melt(graph_data[daily_date >= start_date & daily_date <= extended_end_date, .(daily_date, basis_scaled, hkm_scaled, int_equity, market)], 
                    id.vars = 'daily_date', variable.name = 'Factor', value.name = 'Value'),
        mapping = aes(x = daily_date, y = Value, color = Factor, linetype = Factor)) + 
    geom_line() +
    scale_color_manual(name = '', breaks = c('basis_scaled', 'hkm_scaled', 'int_equity', 'market'),
                       values = c(basis_scaled = 'red', hkm_scaled = 'blue', int_equity = 'brown', market = 'dark green'), 
                       guide = 'legend', labels = c('Spot AUD-JPY 3M Basis (RHS)', 'Scaled HKM Capital Ratio (LHS)',
                                                    'Cumulative Int. Equity Return (LHS)', 'Cumulative Market Return (LHS)')) +
    scale_linetype_manual(name = '', breaks = c('basis_scaled', 'hkm_scaled', 'int_equity', 'market'),
                          values = c(basis_scaled = 'solid', hkm_scaled = 'dashed', int_equity = 'dotted', market = 'dotdash'), 
                          guide = 'legend', labels = c('Spot AUD-JPY 3M Basis (RHS)', 'Scaled HKM Capital Ratio (LHS)',
                                                       'Cumulative Int. Equity Return (LHS)', 'Cumulative Market Return (LHS)')) +
    #scale_size_manual(name = '', breaks = c('Basis Factor', 'HKM Factor', 'Int. Equity', 'Market'),
    #                  values = c(`Basis Factor` = 0.5, `HKM Factor` = 0.1, `Int. Equity` = 0.1, Market = 0.1)) +
    labs(x = '', y = '', title = '') +
    geom_hline(yintercept = 0) +
    scale_x_date(labels = scales::date_format('%Y'), breaks = '2 years') +
    scale_y_continuous('Cumulative return', sec.axis = sec_axis(~ . / .02, name = 'Basis points')) +
    theme(legend.box.margin = margin(t = -1, unit = 'cm'), legend.spacing.x = unit(0.2, 'cm'), legend.title = element_blank()) +
    guides(colour = guide_legend(nrow = 2, byrow = TRUE)) +
    theme_chart +
    theme(legend.text = element_text(size = 16)) +#, family = 'Arial')) + 
    theme(axis.title = element_text(size = 16), axis.text = element_text(size = 10))
)
ggsave(filename = paste0(script_path, 'OutputFinal/', 'Factor_Return_Correlations.png'), width = 10, height = 5, dpi = 300)

#---------------------------------------------------------
# Figure A1: 3M MA spot OIS + IBOR basis
#---------------------------------------------------------

rolling_window <- 10
for (rate in c('ois', 'ibor')) {
  if (rate == 'ois') {
    currency_names <- currency_names_single
  } else if (rate == 'ibor') {
    currency_names <- currency_names_single
  }
  graph_data <- rates_and_dates[Date <= extended_end_date, c('Date', paste(currency_names, rate, 'spot_log_basis_3M', sep = '_')), with = FALSE]
  graph_data[, (currency_names) := lapply(.SD, function(x) c(rep(NA, rolling_window - 1), rollapply(x, width = rolling_window, FUN = mean, na.rm = TRUE, align = 'right'))),
             .SDcols = paste(currency_names, rate, 'spot_log_basis_3M', sep = '_')]
  names(graph_data) <- gsub('_USD', '', names(graph_data))
  (ggplot(data = melt(graph_data[, c('Date', gsub('_USD', '', currency_names)), with = FALSE], id.vars = 'Date', variable.name = 'Currency', value.name = 'Basis'),
          mapping = aes(x = Date, y = Basis * 100, colour = Currency)) +
      geom_line() +
      scale_color_manual(name = 'Currency', breaks = c('AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY'),
                         values = c(AUD = 'black', CAD = 'magenta', CHF = 'darkgreen', EUR = 'green',
                                    GBP = 'blue', JPY = 'red')) +
      labs(x = '', y = 'Basis Points', title = '') +
      geom_hline(yintercept = 0) +
      scale_x_date(labels = scales::date_format('%Y'), breaks = '2 years') +
      theme(legend.box.margin = margin(t = -1, unit = 'cm'), legend.spacing.x = unit(0.2, 'cm'), legend.title = element_blank()) +
      guides(colour = guide_legend(nrow = 1, byrow = TRUE)) +
      theme_chart
  )
  ggsave(filename = paste0(script_path, 'OutputFinal/', 'SpotBasis_', toupper(rate), '_3M.png'), width = 6, height = 5, dpi = 300)
}

#---------------------------------------------------------
# Figure A3: Term structure - OPTION B; grouped HML; select forward tenors
#---------------------------------------------------------

for (rate in c('ois')) {
  if (rate == 'ois') {
    currency_names <- currency_names6
  } else if (rate == 'ibor') {
    currency_names <- currency_names6
  }
  
  for (c in c(which(currency_names == 'AUD'), which(currency_names == 'JPY'))) {
    ts_data <- rates_and_dates[Date >= start_date & Date <= extended_end_date, c('Date', 'period', paste(currency_names[c], 'USD', rate, 'spot_log_basis_3M', sep = '_'),
                                                       paste(currency_names[c], 'USD', rate, 'log_basis_1M_fwd_3M', sep = '_'),
                                                       paste(currency_names[c], 'USD', rate, 'log_basis_3M_fwd_3M', sep = '_'),
                                                       paste(currency_names[c], 'USD', rate, 'log_basis_6M_fwd_3M', sep = '_'),
                                                       paste(currency_names[c], 'USD', rate, 'log_basis_9M_fwd_3M', sep = '_')), with = FALSE]
    names(ts_data) <- c('Date', 'period', 'spot_3M', '1M-fwd 3M', '3M-fwd 3M', '6M-fwd 3M', '9M-fwd 3M')
    ts_data <- ts_data[complete.cases(ts_data)]
    
    for (p in 'Post-Crisis') {
      temp_cut <- ts_data[period == p, ]
      low_mid_cutoff <- quantile(temp_cut$spot_3M, 1/3)
      mid_high_cutoff <- quantile(temp_cut$spot_3M, 2/3)
      
      graph_low <- temp_cut[spot_3M <= low_mid_cutoff, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = names(ts_data)[!(names(ts_data) %in% c('Date', 'period'))]]
      graph_mid <- temp_cut[spot_3M > low_mid_cutoff & spot_3M <= mid_high_cutoff, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = names(ts_data)[!(names(ts_data) %in% c('Date', 'period'))]]
      graph_high <- temp_cut[spot_3M > mid_high_cutoff, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = names(ts_data)[!(names(ts_data) %in% c('Date', 'period'))]]
      
      # Bucket by spot 3M
      graph_data <- data.frame(t(rbind(graph_low, graph_mid, graph_high)))
      names(graph_data) <- c('Low', 'Medium', 'High')
      graph_data$tenor <- factor(c('spot_3M', '1M-fwd 3M', '3M-fwd 3M', '6M-fwd 3M', '9M-fwd 3M'),
                                 levels = c('spot_3M', '1M-fwd 3M', '3M-fwd 3M', '6M-fwd 3M', '9M-fwd 3M'))
      
      temp_title <- paste(currency_names[c])
      temp_file <- paste(currency_names[c], rate, p, 'TS_fwd_select', sep = '_')
      ggplot(data = reshape2::melt(graph_data, id.vars = 'tenor', variable.name = 'Buckets by Spot 3M', value.name = 'Value'),
             mapping = aes(x = tenor, y = Value * 100, colour = `Buckets by Spot 3M`, group = `Buckets by Spot 3M`)) +
        geom_line() +
        geom_point() +
        labs(x = 'Tenor of Basis', y = 'Basis Points', title = temp_title) +
        geom_hline(yintercept = 0) +
        theme_chart
      ggsave(filename = paste0(script_path, 'OutputFinal/', temp_file, '.png'), width = 8, height = 5, dpi = 300)
    }
  }
}

#---------------------------------------------------------
# Figure A4: "Term structure" by quarter-cross - for AUD-JPY Classic Carry
#---------------------------------------------------------

for (rate in c('ois')) {
  currency_names <- currency_names6
  
  # Construct the classic carry spot and forward basis
  ts_data <- rates_and_dates[Date >= start_date & Date <= extended_end_date, c('Date', 'period', paste('AUD', 'USD', rate, 'spot_log_basis_1M', sep = '_'),
                                                     paste('JPY', 'USD', rate, 'spot_log_basis_1M', sep = '_'),
                                                     paste('AUD', 'USD', rate, 'log_basis_1M_fwd_1M', sep = '_'),
                                                     paste('JPY', 'USD', rate, 'log_basis_1M_fwd_1M', sep = '_'),
                                                     paste('AUD', 'USD', rate, 'log_basis_2M_fwd_1M', sep = '_'),
                                                     paste('JPY', 'USD', rate, 'log_basis_2M_fwd_1M', sep = '_')), with = FALSE]
  ts_data <- ts_data[complete.cases(ts_data)]
  ts_data[, portfolio_ois_spot_log_basis_classic_carry_1M := AUD_USD_ois_spot_log_basis_1M - JPY_USD_ois_spot_log_basis_1M]
  ts_data[, portfolio_ois_log_basis_classic_carry_1M_fwd_1M := AUD_USD_ois_log_basis_1M_fwd_1M - JPY_USD_ois_log_basis_1M_fwd_1M]
  ts_data[, portfolio_ois_log_basis_classic_carry_2M_fwd_1M := AUD_USD_ois_log_basis_2M_fwd_1M - JPY_USD_ois_log_basis_2M_fwd_1M]
  
  # Settlement dates based on AUD 
  ts_data <- merge(ts_data[, c('Date', 'period', 'portfolio_ois_spot_log_basis_classic_carry_1M', 'portfolio_ois_log_basis_classic_carry_1M_fwd_1M', 'portfolio_ois_log_basis_classic_carry_2M_fwd_1M'), with = F],
                   list_settlement[['AUD']][, c('Date', 'spot', 'one_mth', 'two_mth', 'three_mth'), with = F], by = 'Date', all.x = T)
  names(ts_data) <- c('Date', 'period', 'spot 1M', '1M-fwd 1M', '2M-fwd 1M', 'settle_spot', 'settle_1M', 'settle_2M', 'settle_3M')
  ts_data[, QE_settle_spot_1M := date_to_QE(settle_spot) != date_to_QE(settle_1M)]
  ts_data[, QE_settle_1M_fwd_1M := date_to_QE(settle_1M) != date_to_QE(settle_2M)]
  ts_data[, QE_settle_2M_fwd_1M := date_to_QE(settle_2M) != date_to_QE(settle_3M)]
  
  for (p in 'Post-Crisis') {
    temp_cut <- ts_data[period == p, ]
    
    graph_QE_spot_1M <- temp_cut[QE_settle_spot_1M == T, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = c('spot 1M', '1M-fwd 1M', '2M-fwd 1M')]
    graph_QE_1M_fwd_1M <- temp_cut[QE_settle_1M_fwd_1M == T, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = c('spot 1M', '1M-fwd 1M', '2M-fwd 1M')]
    graph_QE_2M_fwd_1M <- temp_cut[QE_settle_2M_fwd_1M == T, lapply(.SD, function(x) mean(x, na.rm = TRUE)), .SDcols = c('spot 1M', '1M-fwd 1M', '2M-fwd 1M')]
    
    graph_data <- data.frame(t(rbind(graph_QE_spot_1M, graph_QE_1M_fwd_1M, graph_QE_2M_fwd_1M)))
    names(graph_data) <- c('Spot 1M', '1M-fwd 1M', '2M-fwd 1M')
    graph_data$tenor <- factor(c('Spot 1M', '1M-fwd 1M', '2M-fwd 1M'),
                               levels = c('Spot 1M', '1M-fwd 1M', '2M-fwd 1M'))
    
    temp_file <- paste('classic_carry', rate, p, 'TS_fwd_QE', sep = '_')
    ggplot(data = reshape2::melt(graph_data, id.vars = 'tenor', variable.name = 'Buckets by quarter-crossing OIS tenor', value.name = 'Value'),
           mapping = aes(x = tenor, y = Value * 100, colour = `Buckets by quarter-crossing OIS tenor`, group = `Buckets by quarter-crossing OIS tenor`)) +
      geom_line() +
      geom_point() +
      labs(x = 'Tenor of Basis', y = 'Basis Points', title = '') +
      guides(colour = guide_legend(title = 'Buckets by quarter-crossing OIS tenor')) +
      theme_chart
    ggsave(filename = paste0(script_path, 'OutputFinal/', temp_file, '.png'), width = 8, height = 5, dpi = 300)
  }
}

#---------------------------------------------------------
# Figure A5: Repo volume vs. rate spread
#---------------------------------------------------------
rate_gcf[, `:=` (Date = mdy(Date))]
names(rate_gcf) <- c('Date', 'rate_gcf_mbs', 'rate_gcf_tsy', 'rate_gcf_agc')

names(rate_tpr) <- c('Date', 'rate_tpr_tsy')
rate_tpr[, Date := ymd(Date)]

names(rate_pd_tsy) <- c('Date', 'rate_pd_tsy')
rate_pd_tsy[, `:=` (Date = mdy(Date), rate_pd_tsy = as.numeric(rate_pd_tsy))]

repo_tsy[, Date := dmy(date)]
rate_comp <- Reduce(function(x, y) merge(x, y, by = 'Date', all.x = T),
                    list(repo_tsy[, .(Date, rrp_tsy, rp_tsy)],
                         rate_gcf[, .(Date, rate_gcf_tsy)],
                         rate_tpr[, .(Date, rate_tpr_tsy)],
                         rate_pd_tsy[, .(Date, rate_pd_tsy)]))
rate_comp[, `:=` (spread_gcf_pd = rate_gcf_tsy - rate_pd_tsy,
                  spread_gcf_tpr = rate_gcf_tsy - rate_tpr_tsy)]
rate_comp[, rate_spread_orig_scale := ifelse(is.na(spread_gcf_tpr), spread_gcf_pd, spread_gcf_tpr)]
rate_comp[, rate_spread := ifelse(is.na(spread_gcf_tpr), spread_gcf_pd * 2000, spread_gcf_tpr * 2000)]

ggplot(melt(rate_comp[, c('Date', 'rrp_tsy', 'rp_tsy', 'rate_spread')], id.vars = 'Date'),
       aes(x = Date, y = value, color = variable)) +
  geom_rect(data = data.frame(xmin = ymd('2007-07-01'),
                              xmax = ymd('2010-07-01'),
                              ymin = -Inf,
                              ymax = Inf),
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = 'grey', alpha = 0.5, inherit.aes = F) +
  geom_line(aes(size = variable)) +
  scale_color_manual(values = c('red', 'blue', 'black'),
                     breaks = c('rrp_tsy', 'rp_tsy', 'rate_spread'),
                     labels = c('Tsy repo lending (LHS)', 'Tsy repo borrowing (LHS)', 'Lending vs. borrowing spread (RHS)')) +
  scale_size_manual(values = c(rep(0.5, 2), 1),
                    breaks = c('rrp_tsy', 'rp_tsy', 'rate_spread'),
                    labels = c('Tsy repo lending (LHS)', 'Tsy repo borrowing (LHS)', 'Lending vs. borrowing spread (RHS)')) +
  labs(x = '', y = '', title = '') +
  scale_x_date(labels = scales::date_format('%Y'), breaks = '2 years') +
  scale_y_continuous('Billions USD', sec.axis = sec_axis(~ . / 20, name = 'Basis points')) +
  theme(legend.box.margin = margin(t = -1, unit = 'cm'), legend.spacing.x = unit(0.2, 'cm'), legend.title = element_blank()) +
  guides(colour = guide_legend()) +
  theme_chart +
  theme(legend.text = element_text(size = 16)) +#, family = 'Arial')) +
  theme(axis.title = element_text(size = 16), axis.text = element_text(size = 10))
ggsave(filename = paste0(script_path, 'OutputFinal/repo_rate_comp.png'), width = 10, height = 8, dpi = 300)

######################### END OF FIGURES BEGINNING OF TABLES ##########################

log_table <- file(paste0(script_path, 'OutputFinal/log_tables.txt'), open = 'wt')
sink(log_table, type = 'output', split = TRUE) 

#---------------------------------------------------------
# Table 1: returns of single currency vs USD + correlations
#---------------------------------------------------------

# Single currencies: OIS 1M-fwd 3M only
list_num <- 2
rate <- 'ois'
currency_names <- paste(single_table$fund_currency, single_table$invest_currency, sep = '_')
interest_name <- '3M'

matrix_column <- c('Currency', ' ', period_order, ' ', period_order)#, ' ', 'avg_basis', 'interest_diff')
temp_matrix <- matrix(, nrow = length(currency_names) * 2, ncol = length(matrix_column))
colnames(temp_matrix) <- matrix_column
rounding <- 2

# Read in data and fill out the matrix
for (i in 1:length(currency_names)) {
  temp_matrix[i * 2 - 1, 'Currency'] <- currency_names[i]
  
  temp_matrix[i * 2 - 1, 3:5] <- paste0(format(round(list_single_return[[list_num]][paste(currency_names[i], 'mean'),], rounding), nsmall = rounding),
                                        list_single_mean_star[[list_num]][currency_names[i],])
  temp_matrix[i * 2, 3:5] <- paste0('(', format(round(list_single_return[[list_num]][paste(currency_names[i], 'se_mean'),], rounding), nsmall = rounding), ')')
  temp_matrix[i * 2 - 1, 7:9] <- paste0(format(round(list_single_return[[list_num]][paste(currency_names[i], 'Sharpe'),], rounding), nsmall = rounding),
                                        list_single_Sharpe_star[[list_num]][currency_names[i],])
  temp_matrix[i * 2, 7:9] <- paste0('(', format(round(list_single_return[[list_num]][paste(currency_names[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
}

## Print table preambles
cat('\\begin{sidewaystable}[!ht]  \\centering  \\caption{\\textbf{Forward CIP Trading Profits and Additional Properties for USD-Based Currency Pairs}} \\label{table:single_currencies}')

## Print PART I of table into LaTeX via xtable
xtable_matrix <- xtable(temp_matrix)
align(xtable_matrix) <- c('l', 'l', rep(c('p{0.01\\textwidth}', rep('C{0.1\\textwidth}', length(period_order))), 2))
addtorow <- list()
addtorow$pos <- list(-1, nrow(temp_matrix))
addtorow$command <- c(paste0('\\hline\\hline \\\\ ', 
                             '\\multicolumn{9}{c}{Panel A: Summary Statistics of Returns on OIS 1M-fwd 3M Forward CIP Trading Strategy}',
                             '\\ \\',
                             '\\hline & & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio}',
                             '\\hhline{~~~---~---}',
                             ' & & Pre-GFC & GFC & Post-GFC & & Pre-GFC & GFC & Post-GFC', 
                             '\\hhline{----------}'),
                      paste0('\\hline \\\\'))

print(xtable_matrix, include.rownames = FALSE, include.colnames = FALSE, add.to.row = addtorow, hline.after = NULL, floating = F) 

## Correlations and properties
corr_table[, `:=` (currency = substr(pair, 1, 3),
                   scaled_return = average_return * 100 * 12 / (12 / 3), #annualize x12, adjust for 3M interest duration
                   scaled_slope = average_slope * 100 * 12 / (12 / 3),
                   scaled_basis = average_basis * 100)]
corr_formatted <- corr_table[, .(pair, scaled_return, scaled_basis, scaled_slope, interest_difference, sp_corr_fx)]

## PANEL B
xtable_matrix <- xtable(corr_formatted)
align(xtable_matrix) <- c('l', 'C{0.14\\textwidth}', rep('C{0.13\\textwidth}', ncol(corr_formatted) - 1))
addtorow <- list()
addtorow$pos <- list(-1, 3, nrow(corr_table))
addtorow$command <- c(paste0('\\multicolumn{6}{c}{Panel B: Post-GFC Properties}',
                             '\\ \\',
                             '\\hline & Mean Fwd CIP Trad. Ret. & Average Basis & Average Slope & Avg. Interest Diff. vs. USD & Corr SPX and FX',
                             '\\\\ \\hline'),
                      paste0('\\hline '),
                      paste0('\\hline\\hline')) 

print(xtable_matrix, include.rownames = FALSE, include.colnames = FALSE, add.to.row = addtorow, hline.after = NULL, floating = F) 
cat('\\end{sidewaystable}')

#---------------------------------------------------------
# Tables 2, 3: cross-currency pairs and portfolios in OIS 1M-fwd-3M
#---------------------------------------------------------

# indicate the position of the desired contract within list
portfolio_names_pc <- c('classic carry', 'single 3v3', 'top5 basis', 'equal pairs', 'equal dollar', 'top6 pc') #As in return summary
proper_names_pc <- c('Classic Carry (AUD-JPY)', 'Dollar-neutral Carry', 'Dynamic Top5 Basis', 'Static Top Basis', 'Simple Dollar', 'Basis PC')

# OIS / IBOR 1M-fwd 3M only
for (list_num in c(2, 4)) {
  if ((list_num == 1) | (list_num == 2) | (list_num == 3)){
    rate <- 'ois'
    currency_names <- paste(ois_table$fund_currency, ois_table$invest_currency, sep = '_')
  } else {
    rate <- 'ibor'
    currency_names <- paste(ibor_table$fund_currency, ibor_table$invest_currency, sep = '_')
  }
  
  if (list_num == 1) {
    title_name <- '1M-forward 1M'
    label_name <- '1M_1M'
    interest_name <- '1M'
  } else if (list_num == 2 | list_num == 4) {
    title_name <- '1M-forward 3M'
    label_name <- '1M_3M'
    interest_name <- '3M'
  } else {
    title_name <- '3M-forward 3M'
    label_name <- '3M_3M'
    interest_name <- '3M'
  }
  
  # CURRENCY PAIRS
  matrix_column <- c('Currency', ' ', period_order, ' ', period_order, ' ', 'avg_basis', 'interest_diff')
  temp_matrix <- matrix(, nrow = length(currency_names) * 2, ncol = length(matrix_column))
  colnames(temp_matrix) <- matrix_column
  rounding <- 2
  
  # Read in data and fill out the matrix
  for (i in 1:length(currency_names)) {
    temp_matrix[i * 2 - 1, 'Currency'] <- currency_names[i]
    
    temp_matrix[i * 2 - 1, 3:5] <- paste0(format(round(list_single_return[[list_num]][paste(currency_names[i], 'mean'),], rounding), nsmall = rounding),
                                          list_single_mean_star[[list_num]][currency_names[i],])
    temp_matrix[i * 2, 3:5] <- paste0('(', format(round(list_single_return[[list_num]][paste(currency_names[i], 'se_mean'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 7:9] <- paste0(format(round(list_single_return[[list_num]][paste(currency_names[i], 'Sharpe'),], rounding), nsmall = rounding),
                                          list_single_Sharpe_star[[list_num]][currency_names[i],])
    temp_matrix[i * 2, 7:9] <- paste0('(', format(round(list_single_return[[list_num]][paste(currency_names[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 11] <- format(round(list_interest[[paste(rate, interest_name, sep = '_')]][paste(currency_names[i], rate, interest_name, sep = '_'), c('avg_basis')] * 100, 
                                               rounding), nsmall = rounding)
    temp_matrix[i * 2 - 1, 12] <- format(round(list_interest[[paste(rate, interest_name, sep = '_')]][paste(currency_names[i], rate, interest_name, sep = '_'), c('difference')], 
                                               rounding), nsmall = rounding)
  }
  
  # Print table into LaTeX via xtable
  xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Summary Statistics of Currency Pair Returns on', toupper(rate), title_name, 'Forward CIP Trading Strategy}'), 
                          label = paste('table:summary_currency', rate, label_name, sep = '_'))
  align(xtable_matrix) <- c('l', 'l', rep(c('p{0.001\\textwidth}', rep('C{0.08\\textwidth}', length(period_order))), 2), 'p{0.001\\textwidth}', 'C{0.06\\textwidth}', 'C{0.09\\textwidth}')
  addtorow <- list()
  addtorow$pos <- list(-1, nrow(temp_matrix))
  addtorow$command <- c(paste0('\\hline\\hline', 
                               '& & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio} & & \\multicolumn{2}{c}{Post-GFC Metrics}',
                               '\\hhline{~~~---~---~--}',
                               ' & & Pre-GFC & GFC & Post-GFC & & Pre-GFC & GFC & Post-GFC & & Avg Basis & Int. Rate Diff.',
                               '\\hhline{-------------}'),
                        paste0('\\hline\\hline', 
                               '\\multicolumn{12}{l}{Standard errors in parentheses}'))
  
  print(xtable_matrix, include.rownames = FALSE, add.to.row = addtorow, hline.after = NULL,
        caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable', include.colnames = FALSE) 
  
  # PORTFOLIOS
  matrix_column <- c('Portfolio', ' ', period_order, ' ', period_order)
  temp_matrix <- matrix(, nrow = length(portfolio_names_pc) * 2, ncol = length(matrix_column))
  colnames(temp_matrix) <- matrix_column
  rounding <- 2
  
  # Read in data and fill out the matrix
  for (i in 1:length(portfolio_names_pc)) {
    temp_matrix[i * 2 - 1, 'Portfolio'] <- proper_names_pc[i]
    
    temp_matrix[i * 2 - 1, 3:5] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'mean'),], rounding), nsmall = rounding),
                                          list_portfolio_mean_star[[list_num]][portfolio_names_pc[i],])
    temp_matrix[i * 2, 3:5] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'se_mean'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 7:9] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'Sharpe'),], rounding), nsmall = rounding),
                                          list_portfolio_Sharpe_star[[list_num]][portfolio_names_pc[i],])
    temp_matrix[i * 2, 7:9] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
  }
  
  # Print table into LaTeX via xtable
  xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Summary Statistics of Portfolio Returns on', toupper(rate), title_name, 'Forward CIP Trading Strategy}'), 
                          label = paste('table:summary_portfolio', rate, label_name, sep = '_'))
  align(xtable_matrix) <- c('l', 'l', rep(c('p{0.001\\textwidth}', rep('C{0.10\\textwidth}', length(period_order))), 2))
  addtorow <- list()
  addtorow$pos <- list(-1, nrow(temp_matrix))
  addtorow$command <- c(paste0('\\hline\\hline', 
                               '& & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio}',
                               '\\hhline{~~~---~---}',
                               ' & & Pre-GFC & GFC & Post-GFC & & Pre-GFC & GFC & Post-GFC',
                               '\\hhline{----------}'),
                        paste0('\\hline\\hline', 
                               '\\multicolumn{9}{l}{Standard errors in parentheses}'))
  
  print(xtable_matrix, include.rownames = FALSE, add.to.row = addtorow, hline.after = NULL,
        caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable', include.colnames = FALSE) 
}

#---------------------------------------------------------
# Table 4: POST-GFC (pre/post COVID) cross-currency pairs and portfolios in OIS 1M-fwd-3M
#---------------------------------------------------------

# OIS 1M-fwd 3M only
for (list_num in c(2)) {
  rate <- 'ois'
  if (list_num == 1) {
    title_name <- '1M-forward 1M'
    label_name <- '1M_1M'
    interest_name <- '1M'
  } else if (list_num == 2 | list_num == 4) {
    title_name <- '1M-forward 3M'
    label_name <- '1M_3M'
    interest_name <- '3M'
  } else {
    title_name <- '3M-forward 3M'
    label_name <- '3M_3M'
    interest_name <- '3M'
  }
  
  # PORTFOLIOS
  matrix_column <- c('Portfolio', ' ', covid_order, 'Overall', ' ', covid_order, 'Overall')
  temp_matrix <- matrix(, nrow = length(portfolio_names_pc) * 2, ncol = length(matrix_column))
  colnames(temp_matrix) <- matrix_column
  rounding <- 2
  
  # Read in data and fill out the matrix
  for (i in 1:length(portfolio_names_pc)) {
    temp_matrix[i * 2 - 1, 'Portfolio'] <- proper_names_pc[i]
    
    temp_matrix[i * 2 - 1, 3:4] <- paste0(format(round(list_portfolio_return_covid[[list_num]][paste(portfolio_names_pc[i], 'mean'),], rounding), nsmall = rounding),
                                          list_portfolio_mean_star_covid[[list_num]][portfolio_names_pc[i],])
    temp_matrix[i * 2, 3:4] <- paste0('(', format(round(list_portfolio_return_covid[[list_num]][paste(portfolio_names_pc[i], 'se_mean'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 5] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'mean'), 'Post-Crisis'], rounding), nsmall = rounding),
                                          list_portfolio_mean_star[[list_num]][portfolio_names_pc[i], 'Post-Crisis'])
    temp_matrix[i * 2, 5] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'se_mean'), 'Post-Crisis'], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 7:8] <- paste0(format(round(list_portfolio_return_covid[[list_num]][paste(portfolio_names_pc[i], 'Sharpe'),], rounding), nsmall = rounding),
                                          list_portfolio_Sharpe_star_covid[[list_num]][portfolio_names_pc[i],])
    temp_matrix[i * 2, 7:8] <- paste0('(', format(round(list_portfolio_return_covid[[list_num]][paste(portfolio_names_pc[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 9] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'Sharpe'), 'Post-Crisis'], rounding), nsmall = rounding),
                                          list_portfolio_Sharpe_star[[list_num]][portfolio_names_pc[i], 'Post-Crisis'])
    temp_matrix[i * 2, 9] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'se_Sharpe'), 'Post-Crisis'], rounding), nsmall = rounding), ')')
  }
  
  # Print table into LaTeX via xtable
  xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Pre/Post COVID Statistics of Portfolio Returns on', toupper(rate), title_name, 'Forward CIP Trading Strategy}'), 
                          label = paste('table:covid_portfolio', rate, label_name, sep = '_'))
  align(xtable_matrix) <- c('l', 'l', rep(c('p{0.001\\textwidth}', rep('C{0.10\\textwidth}', length(covid_order) + 1)), 2))
  addtorow <- list()
  addtorow$pos <- list(-1, nrow(temp_matrix))
  addtorow$command <- c(paste0('\\hline\\hline', 
                               '& & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio}',
                               '\\hhline{~~~---~---}',
                               ' & & Pre 2020 & Post 2020 & Overall & & Pre 2020 & Post 2020 & Overall',
                               '\\hhline{----------}'),
                        paste0('\\hline\\hline', 
                               '\\multicolumn{9}{l}{Standard errors in parentheses}'))
  
  print(xtable_matrix, include.rownames = FALSE, add.to.row = addtorow, hline.after = NULL,
        caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable', include.colnames = FALSE) 
}

#---------------------------------------------------------
# Tables A2, A3, A4, A5, A6: return robustness using other interest rates and duration / portfolio only
#---------------------------------------------------------

portfolio_names <- c('classic carry', 'single 3v3', 'top5 basis', 'equal pairs', 'equal dollar', 'top6 pc') #As in return summary
proper_names <- c('Classic Carry (AUD-JPY)', 'Dollar-neutral Carry', 'Dynamic Top5 Basis', 'Static Top Basis', 'Simple Dollar', 'Basis PC')

for (list_num in c(1, 3, 4, 5)) {
  if ((list_num == 1) | (list_num == 2) | (list_num == 3)){
    rate <- 'ois'
    currency_names <- paste(ois_table$fund_currency, ois_table$invest_currency, sep = '_')
  } else {
    rate <- 'ibor'
    currency_names <- paste(ibor_table$fund_currency, ibor_table$invest_currency, sep = '_')
  }
  
  if (list_num == 1) {
    title_name <- '1M-forward 1M'
    label_name <- '1M_1M'
    interest_name <- '1M'
  } else if (list_num == 2 | list_num == 4) {
    title_name <- '1M-forward 3M'
    label_name <- '1M_3M'
    interest_name <- '3M'
  } else {
    title_name <- '3M-forward 3M'
    label_name <- '3M_3M'
    interest_name <- '3M'
  }
  
  # PORTFOLIOS
  matrix_column <- c('Portfolio', ' ', period_order, ' ', period_order)
  temp_matrix <- matrix(, nrow = length(portfolio_names) * 2, ncol = length(matrix_column))
  colnames(temp_matrix) <- matrix_column
  rounding <- 2
  
  # Read in data and fill out the matrix
  for (i in 1:length(portfolio_names)) {
    temp_matrix[i * 2 - 1, 'Portfolio'] <- proper_names[i]
    
    temp_matrix[i * 2 - 1, 3:5] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names[i], 'mean'),], rounding), nsmall = rounding),
                                          list_portfolio_mean_star[[list_num]][portfolio_names[i],])
    temp_matrix[i * 2, 3:5] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names[i], 'se_mean'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 7:9] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names[i], 'Sharpe'),], rounding), nsmall = rounding),
                                          list_portfolio_Sharpe_star[[list_num]][portfolio_names[i],])
    temp_matrix[i * 2, 7:9] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
  }
  
  # Print table into LaTeX via xtable
  xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Summary Statistics of Portfolio Returns on', toupper(rate), title_name, 'Forward CIP Trading Strategy}'), 
                          label = paste('table:summary_portfolio', rate, label_name, sep = '_'))
  align(xtable_matrix) <- c('l', 'l', rep(c('p{0.001\\textwidth}', rep('C{0.10\\textwidth}', length(period_order))), 2))
  addtorow <- list()
  addtorow$pos <- list(-1, nrow(temp_matrix))
  addtorow$command <- c(paste0('\\hline\\hline', 
                               '& & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio}',
                               '\\hhline{~~~---~---}',
                               ' & & Pre-GFC & GFC & Post-GFC & & Pre-GFC & GFC & Post-GFC',
                               '\\hhline{----------}'),
                        paste0('\\hline\\hline', 
                               '\\multicolumn{9}{l}{Standard errors in parentheses}'))
  
  print(xtable_matrix, include.rownames = FALSE, add.to.row = addtorow, hline.after = NULL,
        caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable', include.colnames = FALSE) 
}

#---------------------------------------------------------
# Tables A7: return robustness using MONTHLY portfolios (no 1M-f-1M)
#---------------------------------------------------------

for (list_num in c(1, 2, 3, 4)) {
  if ((list_num == 1) | (list_num == 2)){
    rate <- 'ois'
    currency_names <- paste(ois_table$fund_currency, ois_table$invest_currency, sep = '_')
  } else {
    rate <- 'ibor'
    currency_names <- paste(ibor_table$fund_currency, ibor_table$invest_currency, sep = '_')
  }
  
  if (list_num == 1 | list_num == 3) {
    title_name <- '1M-forward 3M'
    label_name <- '1M_3M'
    interest_name <- '3M'
  } else {
    title_name <- '3M-forward 3M'
    label_name <- '3M_3M'
    interest_name <- '3M'
  }
  
  # PORTFOLIOS
  matrix_column <- c('Portfolio', ' ', period_order, ' ', period_order)
  temp_matrix <- matrix(, nrow = length(portfolio_names) * 2, ncol = length(matrix_column))
  colnames(temp_matrix) <- matrix_column
  rounding <- 2
  
  # Read in data and fill out the matrix
  for (i in 1:length(portfolio_names)) {
    temp_matrix[i * 2 - 1, 'Portfolio'] <- proper_names[i]
    
    temp_matrix[i * 2 - 1, 3:5] <- paste0(format(round(list_monthly_return[[list_num]][paste(portfolio_names[i], 'mean'),], rounding), nsmall = rounding),
                                          list_monthly_Sharpe_star[[list_num]][portfolio_names[i],])
    temp_matrix[i * 2, 3:5] <- paste0('(', format(round(list_monthly_return[[list_num]][paste(portfolio_names[i], 'se_mean'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 7:9] <- paste0(format(round(list_monthly_return[[list_num]][paste(portfolio_names[i], 'Sharpe'),], rounding), nsmall = rounding),
                                          list_monthly_Sharpe_star[[list_num]][portfolio_names[i],])
    temp_matrix[i * 2, 7:9] <- paste0('(', format(round(list_monthly_return[[list_num]][paste(portfolio_names[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
  }
  
  # Print table into LaTeX via xtable
  xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Summary Statistics of Non-Overlapping Monthly Portfolio Returns on', toupper(rate), title_name, 'Forward CIP Trading Strategy}'), 
                          label = paste('table:summary_monthly', rate, label_name, sep = '_'))
  align(xtable_matrix) <- c('l', 'l', rep(c('p{0.001\\textwidth}', rep('C{0.10\\textwidth}', length(period_order))), 2))
  addtorow <- list()
  addtorow$pos <- list(-1, nrow(temp_matrix))
  addtorow$command <- c(paste0('\\hline\\hline', 
                               '& & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio}',
                               '\\hhline{~~~---~---}',
                               ' & & Pre-GFC & GFC & Post-GFC & & Pre-GFC & GFC & Post-GFC',
                               '\\hhline{----------}'),
                        paste0('\\hline\\hline', 
                               '\\multicolumn{9}{l}{Standard errors in parentheses}'))
  
  print(xtable_matrix, include.rownames = FALSE, add.to.row = addtorow, hline.after = NULL,
        caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable', include.colnames = FALSE) 
}

#---------------------------------------------------------
# Tables A8: POST-GFC (pre/post 2015) cross-currency pairs and portfolios in OIS 1M-fwd-3M
#---------------------------------------------------------

# OIS 1M-fwd 3M only
for (list_num in c(2)) {
  rate <- 'ois'
  if (list_num == 1) {
    title_name <- '1M-forward 1M'
    label_name <- '1M_1M'
    interest_name <- '1M'
  } else if (list_num == 2 | list_num == 4) {
    title_name <- '1M-forward 3M'
    label_name <- '1M_3M'
    interest_name <- '3M'
  } else {
    title_name <- '3M-forward 3M'
    label_name <- '3M_3M'
    interest_name <- '3M'
  }
  
  # PORTFOLIOS
  matrix_column <- c('Portfolio', ' ', slr_order, 'Overall', ' ', slr_order, 'Overall')
  temp_matrix <- matrix(, nrow = length(portfolio_names_pc) * 2, ncol = length(matrix_column))
  colnames(temp_matrix) <- matrix_column
  rounding <- 2
  
  # Read in data and fill out the matrix
  for (i in 1:length(portfolio_names_pc)) {
    temp_matrix[i * 2 - 1, 'Portfolio'] <- proper_names_pc[i]
    
    temp_matrix[i * 2 - 1, 3:4] <- paste0(format(round(list_portfolio_return_slr[[list_num]][paste(portfolio_names_pc[i], 'mean'),], rounding), nsmall = rounding),
                                          list_portfolio_mean_star_slr[[list_num]][portfolio_names_pc[i],])
    temp_matrix[i * 2, 3:4] <- paste0('(', format(round(list_portfolio_return_slr[[list_num]][paste(portfolio_names_pc[i], 'se_mean'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 5] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'mean'), 'Post-Crisis'], rounding), nsmall = rounding),
                                        list_portfolio_mean_star[[list_num]][portfolio_names_pc[i], 'Post-Crisis'])
    temp_matrix[i * 2, 5] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'se_mean'), 'Post-Crisis'], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 7:8] <- paste0(format(round(list_portfolio_return_slr[[list_num]][paste(portfolio_names_pc[i], 'Sharpe'),], rounding), nsmall = rounding),
                                          list_portfolio_Sharpe_star_slr[[list_num]][portfolio_names_pc[i],])
    temp_matrix[i * 2, 7:8] <- paste0('(', format(round(list_portfolio_return_slr[[list_num]][paste(portfolio_names_pc[i], 'se_Sharpe'),], rounding), nsmall = rounding), ')')
    temp_matrix[i * 2 - 1, 9] <- paste0(format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'Sharpe'), 'Post-Crisis'], rounding), nsmall = rounding),
                                        list_portfolio_Sharpe_star[[list_num]][portfolio_names_pc[i], 'Post-Crisis'])
    temp_matrix[i * 2, 9] <- paste0('(', format(round(list_portfolio_return[[list_num]][paste(portfolio_names_pc[i], 'se_Sharpe'), 'Post-Crisis'], rounding), nsmall = rounding), ')')
  }
  
  # Print table into LaTeX via xtable
  xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Pre/Post SLR Statistics of Portfolio Returns on', toupper(rate), title_name, 'Forward CIP Trading Strategy}'), 
                          label = paste('table:slr_portfolio', rate, label_name, sep = '_'))
  align(xtable_matrix) <- c('l', 'l', rep(c('p{0.001\\textwidth}', rep('C{0.10\\textwidth}', length(slr_order) + 1)), 2))
  addtorow <- list()
  addtorow$pos <- list(-1, nrow(temp_matrix))
  addtorow$command <- c(paste0('\\hline\\hline', 
                               '& & \\multicolumn{3}{c}{Mean} & & \\multicolumn{3}{c}{Sharpe Ratio}',
                               '\\hhline{~~~---~---}',
                               ' & & Pre 2015 & Post 2015 & Overall & & Pre 2015 & Post 2015 & Overall',
                               '\\hhline{----------}'),
                        paste0('\\hline\\hline', 
                               '\\multicolumn{9}{l}{Standard errors in parentheses}'))
  
  print(xtable_matrix, include.rownames = FALSE, add.to.row = addtorow, hline.after = NULL,
        caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable', include.colnames = FALSE) 
}

#---------------------------------------------------------
# Table A12: returns QE-crossing forwards
#---------------------------------------------------------

dat <- basis_and_returns[period == 'Post-Crisis', c('Date', 'portfolio_ois_log_return_classic_carry_1M_fwd_1M'), with = FALSE]
dat <- merge(dat, list_settlement[['AUD']][, c('Date', 'spot', 'one_mth', 'two_mth'), with = F], by = 'Date', all.x = T)
names(dat) <- c('Date', 'return', 'settle_spot', 'settle_1M', 'settle_2M')
dat[, QE_settle_fwd := date_to_QE(settle_spot) != date_to_QE(settle_1M)]
dat[, QE_settle_int := date_to_QE(settle_1M) != date_to_QE(settle_2M)]
dat[, YE_settle_fwd := year(settle_spot) != year(settle_1M)]
dat[, YE_settle_int := year(settle_1M) != year(settle_2M)]

lm1 <- lm(return ~ 1, data = dat)
lm2 <- lm(return ~ QE_settle_int, data = dat)
lm3 <- lm(return ~ QE_settle_fwd, data = dat)
lm4 <- lm(return ~ QE_settle_int + QE_settle_fwd, data = dat)
lm5 <- lm(return ~ YE_settle_int, data = dat)
lm6 <- lm(return ~ YE_settle_fwd, data = dat)
lm7 <- lm(return ~ YE_settle_int + YE_settle_fwd, data = dat)
lm8 <- lm(return ~ QE_settle_int + QE_settle_fwd + YE_settle_int + YE_settle_fwd, data = dat)

list_lm <- list(lm1, lm2, lm3, lm4, lm5, lm6, lm7, lm8)
list_se <- list()
for (l in 1:length(list_lm)) {
  list_se[[l]] <- sqrt(diag(NeweyWest(list_lm[[l]])))  
}

# F-test for 4, 7
list_f <- list()
for (l in 1:length(list_lm)) {
  b <- list_lm[[l]]$coefficients[-1]
  sigma <- NeweyWest(list_lm[[l]])[-1, -1]
  if (l == 4 | l == 7) {
    R <- matrix(c(1, -1, 1, 0), nrow = 2, byrow = T)
    list_f[[l]] <- round(t(R %*% b) %*% solve(R %*% sigma %*% t(R)) %*% (R%*%b) / nrow(R), 3)
  } else if (l == 8) {
    R <- matrix(c(1, -1, 0, 0, 0, 1, -1, 0, 0, 0, 1, -1, 1, 0, 0, 0), nrow = 4, byrow = T)
    list_f[[l]] <- round(t(R %*% b) %*% solve(R %*% sigma %*% t(R)) %*% (R%*%b) / nrow(R), 3)
  } else {
    list_f[[l]] <- ''
  }
}

stargazer(lm1, lm2, lm3, lm4, lm5, lm6, lm7, lm8, type = 'latex',
          se = list_se,
          covariate.labels = c('QE Cross: Interest Tenor', 'QE Cross: Forward Horizon', 'YE Cross: Interest Tenor', 'YE Cross: Forward Horizon'),
          title = '\\textbf{Returns on Quarter- and Year-end Crossing Forward CIP Trading Strategy Returns}',
          dep.var.labels   = 'OIS 1M-Forward 1M Returns',
          dep.var.caption = '',
          df = FALSE,
          label = 'table:QE',
          omit.stat = c('adj.rsq', 'f'),
          add.lines = list(c('F-stat', unlist(list_f))),
          notes.label = 'Standard errors are in parentheses',
          notes.append = FALSE,
          notes = '',
          float.env = 'sidewaystable')

#---------------------------------------------------------
# Table A31: summary stats of near-arbitrages
#---------------------------------------------------------

near_arb[, Date := dmy(date)]
near_arb <- create_sample_period(number_of_periods = number_of_periods, data_table = near_arb,
                                  date_variable = 'Date', period_order = period_order)
near_arb[, classic_carry_pct := basis_and_returns$factor_ois_spot_3M_classic_carry[match(near_arb$Date, basis_and_returns$Date)]] #has NA in PRE
near_arb[, classic_carry := classic_carry_pct * 100]

matrix_column <- c('Period', 'CIP', 'Bond-CDS', 'CDS-CDX', 'Tenor basis', 'Tsy-swap spread', 'Refco-Tsy spread', 'KfW-Bund spread', 'TIPS-Tsy spread')
temp_matrix <- matrix(, nrow = length(period_order) * 2, ncol = length(matrix_column))
colnames(temp_matrix) <- matrix_column
rounding <- 1

# Read in data and fill out the matrix
for (i in 1:length(period_order)) {
  temp_matrix[i * 2 - 1, 'Period'] <- period_order[i]

  temp_matrix[i * 2 - 1, 2:ncol(temp_matrix)] <- format(round(near_arb[period == period_order[i], lapply(.SD, function(x) mean(x, na.rm = T)),
                                                                        .SDcols = c('classic_carry', 'bond_cds', 'neg_cdx_basis', 'tenor_basis', 'neg_swap_spread',
                                                                                    'refco_treas', 'kfw_bund', 'tips_treas')], rounding), nsmall = rounding)
  temp_matrix[i * 2, 2:ncol(temp_matrix)] <- paste0('(', format(round(near_arb[period == period_order[i], lapply(.SD, function(x) sd(x, na.rm = T)),
                                                                                .SDcols = c('classic_carry', 'bond_cds', 'neg_cdx_basis', 'tenor_basis', 'neg_swap_spread',
                                                                                            'refco_treas', 'kfw_bund', 'tips_treas')], rounding), nsmall = rounding), ')')
}

xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Summary Statistics of CIP and Near-Arbitrage Bases}'),
                        label = paste('table:summ_arb_basis'))
align(xtable_matrix) <- c('l', 'l', rep('C{0.10\\textwidth}', ncol(temp_matrix) - 1))
addtorow <- list()
addtorow$pos <- list(-1, nrow(temp_matrix))
addtorow$command <- c(paste0('\\hline'),
                      paste0('\\hline'))

print(xtable_matrix, include.rownames = FALSE, include.colnames = T, add.to.row = addtorow, #hline.after = NULL,
      caption.placement = 'top', table.placement = '!ht', floating.environment = 'sidewaystable')

#---------------------------------------------------------
# Table A32: price of risk
#---------------------------------------------------------

# Time series mean of excess HKM and market return based on MONTHLY observations
# Note that the risk-free rates are NOT lagged and annualized, returns are from t-1 to t
monthly_returns <- portfolio_monthly[, c('Date', 'USD_ois_1M', 'Tbill_1M', 'Mkt'), with = F]
names(monthly_returns)[which(names(monthly_returns) == 'Mkt')] <- 'mkt_gross'
monthly_returns[, hkm_gross := hkm[, intermediary_value_weighted_investment_return][match(unlist(monthly_returns[, Date]), unlist(hkm[, yyyymm]))]]
monthly_returns[, risk_free := shift(ifelse(is.na(USD_ois_1M), Tbill_1M, USD_ois_1M) / 12, type = 'lag')] 
monthly_returns <- monthly_returns[Date <= 202012]
monthly_returns[, `:=` (hkm_net = hkm_gross - risk_free, 
                        mkt_net = mkt_gross - risk_free)]

hkm_mean <- mean(monthly_returns[, hkm_net], na.rm = T)
mkt_mean <- mean(monthly_returns[, mkt_net], na.rm = T)
carry_mean <- mean(basis_and_returns[Date >= post_crisis_date & Date <= trading_end_date, portfolio_ois_log_return_top6_pc_1M_fwd_3M], na.rm = T) / 100 #basis_and_return are in pp

# Var-cov and estimates of beta
monthly_returns[, carry_net := portfolio_monthly[, pc1top6_ois_1M_fwd_3M][match(unlist(monthly_returns[, Date]), unlist(portfolio_monthly[, Date]))]]
monthly_panel <- monthly_returns[complete.cases(monthly_returns[, c('carry_net', 'hkm_net')])]
monthly_panel <- monthly_panel[Date >= 201007 & Date <= 202012]
monthly_corr <- cov(monthly_panel[, c('hkm_net', 'carry_net'), with = F]) #COV
corr <- cor(monthly_panel[, c('hkm_net', 'carry_net'), with = F]) #CORR
monthly_coef <- solve(monthly_corr) %*% matrix(c(hkm_mean, carry_mean), nrow = 2)

# Find SE of the lambda estimate via delta method, and SE of mean via NW
nw_corr <- lrvar(cbind(monthly_panel$hkm_net, monthly_panel$carry_net), 
                 type = 'Newey-West') # NOTE, the package automatically divided by T already
est_corr <- solve(monthly_corr) %*% nw_corr %*% solve(monthly_corr)
se_corr <- sqrt(diag(est_corr))

lm_carry <- lm(portfolio_ois_log_return_top6_pc_1M_fwd_3M ~ 1, data = basis_and_returns[Date >= post_crisis_date & Date <= trading_end_date])
nw_carry <- sqrt(NeweyWest(lm_carry))
lm_hkm <- lm(hkm_net ~ 1, data = monthly_returns)
nw_hkm <- sqrt(NeweyWest(lm_hkm))

matrix_column <- c('Intermediary Equity Return', 'PC of Fwd. CIP Trading Strategy Ret.')
matrix_row <- c('Price of risk', '.', 'SDF parameters', '..')
temp_matrix <- matrix(, nrow = length(matrix_row), ncol = length(matrix_column))
colnames(temp_matrix) <- matrix_column
rownames(temp_matrix) <- matrix_row
rounding <- 3

temp_matrix[1, ] <- c(hkm_mean, carry_mean) * 1e2
temp_matrix[2, ] <- c(nw_hkm * 1e2, nw_carry)
temp_matrix[3, ] <- monthly_coef
temp_matrix[4, ] <- se_corr

xtable_matrix <- xtable(temp_matrix, caption = paste('\\textbf{Price of Risk and SDF Parameters}'), 
                        label = paste('table:riskprice'), digits = rounding)
align(xtable_matrix) <- c('l', rep('C{0.3\\textwidth}', 2))
addtorow <- list()
addtorow$pos <- list(-1, nrow(temp_matrix))
addtorow$command <- c(paste0('\\hline'),
                      paste0('\\hline'))

as_is <- function(str) {gsub('.', ' ', str, fixed = TRUE)}
print(xtable_matrix, include.rownames = T, include.colnames = T, add.to.row = addtorow, sanitize.rownames.function = as_is, #hline.after = NULL,
      caption.placement = 'top', table.placement = '!ht') 

# make_stars(temp_matrix[1, ] / temp_matrix[2, ], nrow(monthly_panel) - 1)
# make_stars(temp_matrix[3, ] / temp_matrix[4, ], nrow(monthly_panel) - 1)

closeAllConnections()
file.show(paste0(script_path, 'OutputFinal/log_tables.txt'))
